package com.hmall.search.listener;

import com.hmall.common.Constant.OrderConstant;
import com.hmall.common.clients.ItemClient;
import com.hmall.common.clients.OrderClient;
import com.hmall.common.dto.Order;
import com.hmall.common.dto.OrderDetail;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class DelayListener {
    @Autowired
    OrderClient orderClient;
    @Autowired
    ItemClient itemClient;
    
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "delay.queue", durable = "true"),
            exchange = @Exchange(name = "delay.direct", delayed = "true"),
            key = "delay"
    ))
    @GlobalTransactional
    public void delayQueue(String meg) {
        if (meg == null || "".equals(meg)) {
            throw new RuntimeException("meg对象为空或为空字符串");
        }
        Long orderId = Long.parseLong(meg);
        Order order = orderClient.queryOrderById(orderId);
        if (order == null) {
            throw new RuntimeException("order对象为空");
        }
        if (order.getStatus() == OrderConstant.PENDING_PAYMENT){
            //获取订单详细信息,拿取里面的购买数量
            //如果一个订单下购买了多个商品，则需要查询获取一个集合
            OrderDetail orderDetail = orderClient.findOrderDetailByOrderId(orderId);
            if (orderDetail == null) {
                throw new RuntimeException("orderDetail对象为空");
            }
            //修改订单状态为已取消
            orderClient.updateOrderStatus(orderId,OrderConstant.TRANSACTION_FAILED);
            //恢复库存
            itemClient.restoreStock(orderDetail.getItemId(),orderDetail.getNum());
        }
    }
}
